package com.rico.deploy.controller;

import com.rico.common.response.MessageUtils;
import com.rico.common.response.RestResponse;
import com.rico.deploy.entity.User;
import com.rico.deploy.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author 吴泽胜
 * @FileName UserloginController
 * @date 2021-04-23 5:14 下午
 * @Software: IntelliJ IDEA
 */
@Controller
@Slf4j
public class UserloginController {

    @Autowired
    private UserloginService userloginService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public RestResponse login(@RequestParam String username, @RequestParam String password, Model model, HttpSession session){
        log.info("用户{}正在尝试登陆，密码为{}",username, password);
        User user = null;
        if( userloginService.selectUserloginByUAndP(username, password) != null ){
            // 查询个人信息
            user = userService.selectUserByUsername(username);
            if (user != null )
                user.setRolesId(rolesService.selectRolesById(Integer.parseInt(user.getRolesId())).getRolesName());
            session.setAttribute("userinfo",user);
        }else {
            return MessageUtils.fail("登录失败，账号或密码错误");
        }
        return MessageUtils.success("登录成功",user);
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("userinfo");
        session.invalidate();
        return "index";
    }


    @GetMapping("/login.html")
    public String getlogin(){
        return "login";
    }


}
